package com.topteam.component.freemarker;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import com.topteam.frame.controllor.BaseController;
import com.topteam.security.UserSession;
import com.topteam.utility.StringUtil;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

public class TopSelect extends TopTemplateModel {

	public final static String TAG = "select";

	private BaseController controller;

	private String id;

	private String name;

	private String value;

	private String style;

	private String action;
	
	private String lableName;
	
	private String onSelect;

	public TopSelect(BaseController controller) {
		this.controller = controller;
	}

	private void initPara(Map para, Environment env) throws TemplateException {
		id = getStrPara("id", para, env);
		if (StringUtil.isNull(id)) {
			throw new TemplateException("必须直接按钮id的值", env);
		}

		name = getStrPara("name", para, env);
		value = getStrPara("value", para, env);
		style = getStrPara("style", para, env);
		action = getStrPara("action", para, env);
		lableName = getStrPara("lableName", para, env);
		onSelect = getStrPara("onSelect", para, env);
	}

	@Override
	public void execute(Environment env, Map para, TemplateModel[] arg2,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		initPara(para, env);
		Writer w = env.getOut();
		w.write("<select id=\"");
		w.write(id);
		w.write("\" class=\"easyui-combobox\" ");
		if(StringUtil.isNotNull(name))
			w.write("name=\""+name+"\"");
		if(StringUtil.isNotNull(style))
			w.write(" style=\""+style+"\"");
		w.write(">\r\n");
		try{
			body.render(w);
		}catch (NullPointerException e) {
		}
		w.write("</select>");
		if(StringUtil.isNotNull(lableName)){
			w.write("<input id='"+id+"-label' type='hidden' name='"+lableName+"'>");
		}
		writeScript(w);
	}

	public void writeScript(Writer w) throws IOException {
		w.write("<script type=\"text/javascript\">\r\n");
		if (StringUtil.isNotNull(action)) {
			w.write("$(function(){\r\n");
			w.write("	$('#"
					+ id
					+ "').combobox({url:'"
					+ action
					+ "',valueField:'value',textField:'label',onLoadSuccess:function(){$('#"
					+ id + "').combobox('select','" + value + "');},onSelect:function(select){");
			if(StringUtil.isNotNull(lableName)){
				w.write("$('#"+id+"-label').val(select.text);");
			}
			w.write(onSelect+"}});");
			w.write("});\r\n");
		}else{
			w.write("$(function(){\r\n");
			if(StringUtil.isNotNull(value)){
				w.write("	$('#"
						+ id
						+ "').combobox('select','"+value+"');");
			}
			if(StringUtil.isNotNull(lableName)){
				w.write("	$('#"
						+ id
						+ "').combobox({onSelect:function(select){$('#"+id+"-label').val(select.text);");
				w.write(onSelect+"}});");
			}
			w.write("});\r\n");
		}
		
		w.write("</script>");
	}
}
